package com.bytedance.improvingroad.widget

import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.widget.LinearLayout
import androidx.annotation.RequiresApi
import androidx.core.view.NestedScrollingParent
import java.lang.Math.abs

/**
 * Created by chenxiong
 * date 1/23/22
 */
class TraditionalNestedView  @JvmOverloads constructor(
    context: Context,
    attr: AttributeSet? = null,
    style: Int = 0
) : LinearLayout(context, attr, style) {

    var mLastY = 0f
    var mTouchSlop  = 0
    var mTopViewHeight = 0

    init {
        mTouchSlop = ViewConfiguration.get(context).scaledTouchSlop
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mTopViewHeight = getChildAt(0).measuredHeight
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val layoutParams = getChildAt(2).layoutParams
        layoutParams.height = measuredHeight - getChildAt(1).measuredHeight
        getChildAt(2).layoutParams = layoutParams
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        val y = ev.y
        when(ev.action) {
            MotionEvent.ACTION_MOVE -> {
                val dy = mLastY - y
                if (abs(dy) > mTouchSlop) {
                    if (isHiddenTop(dy) || isShowTop(dy)) {
                        //可滚动头部
                        return true
                    }
                }
            }
        }
        mLastY = y
        return super.onInterceptTouchEvent(ev)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val y = event.y
        when(event.action) {
            MotionEvent.ACTION_MOVE -> {
                val dy = mLastY - y
                if (abs(dy) > mTouchSlop) {
                    scrollBy(0, dy.toInt())
                }
            }
        }
        mLastY = y
        return super.onTouchEvent(event)
    }


    private fun isShowTop(dy: Float): Boolean {
        return dy < 0 && scrollY > 0 && !canScrollVertically(-1)
    }

    private fun isHiddenTop(dy: Float): Boolean {
        return dy > 0 && scrollY < mTopViewHeight
    }

    override fun scrollTo(x: Int, y: Int) {
        var tempY = y
        if (y < 0) {
            tempY = 0
        }
        if (y > mTopViewHeight) {
            tempY = mTopViewHeight
        }
        super.scrollTo(x, tempY)
    }
}
